<?php

namespace app\api\middleware;

use app\api\logic\Jwt;

use think\facade\Config;
use think\facade\Log;

class AuthCheck
{
    public function handle($request, \Closure $next)
    {
        Log::write('middleware','myLog');

        //控制器
        $controller = $request->controller(true);
        //方法
        $action = $request->action(true);


        // 不需要登录处理
        $noNeedLoginConfig = Config::get('no_need_login');
        if (isset($noNeedLoginConfig[$controller])) {
            if ($noNeedLoginConfig[$controller] === '*' || in_array($action,$noNeedLoginConfig[$controller])) {
                return $next($request);
            }
        }

        $token = $request->header('authorization');
        $jwt = new Jwt();
        $userInfo = $jwt->decrypt(trim(str_ireplace('Bearer','',$token)));
        Log::write('middleware','myLog');
        Log::write($userInfo,'myLog');
        if ($userInfo === false) {
            return json('no',401);
        }
        $request->userInfo = $userInfo['data'];




        return $next($request);
    }

}